<template>
  <div class="page-container">
    <van-swipe class="swipe-container" :autoplay="3000">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img v-lazy="image">
      </van-swipe-item>
    </van-swipe>
    <div class="goods-list__title">商品</div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="list.length === 0 ? '暂无数据' : '没有更多了'"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.id">
          <div slot="default">
            <div class="goods-container">
              <van-image
                width="80px"
                height="80px"
                fit="cover"
                :src="item.image"
                class="van-col imageBorder"
              />
              <van-row class="content-box" @click.native="detailGo(item)">
                <div class="content-name">{{ item.store_name }}</div>
                <div class="content-des">{{ item.store_introduce }}</div>
                <div v-if="isLogin" class="content-price">
                  ￥{{ item.price }}
                </div>
              </van-row>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    <van-tabbar
      v-model="tabbarActive"
      class="page-tottom-tabbar"
      @change="changeTabbar"
    >
      <van-tabbar-item name="home" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item name="case" icon="star-o">数据</van-tabbar-item>
      <van-tabbar-item name="package" icon="bag-o">订单</van-tabbar-item>
      <van-tabbar-item name="personal" icon="friends-o">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { userInfo } from '@/api/user'
import { rotation, list } from '@/api/goods'
import { getURLParam } from '@/utils/common'
import {
  Button,
  Tabbar,
  TabbarItem,
  Swipe,
  SwipeItem,
  List,
  PullRefresh,
  Card,
  Dialog
} from 'vant'
export default {
  name: 'Home',
  components: {
    [Button.name]: Button,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [List.name]: List,
    [PullRefresh.name]: PullRefresh,
    [Card.name]: Card
  },
  data() {
    return {
      tabbarActive: 'home',
      images: [], // 轮播图
      list: [],
      loading: false,
      finished: false,
      refreshing: false,
      filterData: {
        limit: 10,
        page: 0
        // store_id: localStorage.getItem('adl_store_id')
      },
      storeId: null,
      isLogin: true
    }
  },
  created() {
    this.getSwipeArr()
    if (getURLParam('store_id')) {
      localStorage.setItem('adl_store_id', getURLParam('store_id'))
    }
    if (getURLParam('store_name')) {
      localStorage.setItem(
        'adl_store_name',
        decodeURI(getURLParam('store_name'))
      )
    }
  },
  methods: {
    // 获取轮播图
    getSwipeArr() {
      rotation().then((res) => {
        if (res.error.code === 0) {
          const swipeArr = res.data.map((item) => item.img)
          this.images = swipeArr
        }
      })
    },
    // 获取用户信息，作用：未登录门店id=0
    async getUser() {
      await userInfo().then((res) => {
        if (res.error.code === 0) {
          this.isLogin = true
          this.filterData.store_id = res.data.store_id
          const beforeStoreId = res.data.store_id // 绑定的id
          const beforeStoreName = res.data.store_name // 绑定的name
          const nowStoreId = localStorage.getItem('adl_store_id') // 现在扫码的id
          if (Number(nowStoreId) !== beforeStoreId && !window.HAS_TIPS) {
            Dialog.confirm({
              title: '',
              message: `您已经注册到【${beforeStoreName}】`,
              showCancelButton: false
            }).then(() => {
              window.HAS_TIPS = true // 判断全局变量，用于处理扫码进首页重复判断“您已绑定**门店”
              localStorage.setItem('adl_store_id', beforeStoreId) // 提示完后把本地存储的门店id改成绑定的，这样就不会每次到首页都跳弹框
            })
          }
        } else {
          this.isLogin = false
          this.filterData.store_id = 0
        }
      })
    },
    // 列表
    async getList(refresh) {
      const _self = this
      await list(this.filterData).then((res) => {
        if (res.error.code === 0) {
          // 加载状态结束
          _self.loading = false
          // 数据全部加载完成
          if (refresh === 'refresh') {
            this.list = res.data.list
          } else {
            const tempList = [...this.list, ...res.data.list]
            this.list = tempList
          }
          if (this.list.length >= res.data.totalCount) {
            _self.finished = true
          } else {
            _self.finished = false
          }
        }
      })
    },
    async onLoad() {
      this.filterData.page += 1
      await this.getUser()
      await this.getList()
    },
    onRefresh() {
      this.refreshing = false
      this.finished = true // 防止下拉刷新发送了两次请求的问题
      this.filterData.page = 1
      this.getList('refresh')
      this.list = []
    },
    // 切换菜单
    changeTabbar(e) {
      if (e === 'home') {
        this.$router.push({ name: 'home' })
      } else if (e === 'case') {
        this.$router.push({ name: 'case' })
      } else if (e === 'package') {
        this.$router.push({ name: 'package' })
      } else if (e === 'personal') {
        this.$router.push({ name: 'personal' })
      }
    },
    // 进入详情
    detailGo(item) {
      if (this.isLogin) {
        this.$router.push({
          name: 'homeDetails',
          query: {
            id: item.id
          }
        })
      } else {
        Dialog.confirm({
          title: '',
          message: '您还未登录/注册！',
          showCancelButton: false
        }).then(() => {})
      }
    }
  }
}
</script>
<style lang="less" scoped>
.van-pull-refresh {
  .van-list {
    // 225(轮播)+50(padding-bottom: 50px;)+26(商品标题)
    min-height: calc(100vh - 301px);
  }
}
.page-container {
  padding-bottom: 50px;
  box-sizing: border-box;
  overflow: auto;
}
.swipe-container {
  height: 225px;
}
.swipe-container img {
  display: inline-block;
  width: 100%;
  height: 225px;
}
.goods-list__title {
  color: #323233;
  font-weight: 500;
  font-size: 16px;
  text-align: center;
}
.goods-container {
  padding: 5px;
}
.content-box {
  background-color: #fff;
}
.van-cell {
  margin-bottom: 10px;
  border-radius: 3px;
  padding: 0;
}
.van-list .van-cell {
  box-shadow: 0px 10px 13px -13px #c7d3ed;
}
.van-cell:not(:last-child)::after {
  border-bottom: 0;
}
.imageBorder {
  margin-right: 10px;
}
.content-name {
  font-size: 15px;
}
.content-des {
  color: #cbcbcb;
}
.content-price {
  color: #e56015;
}
</style>
